package rtmp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class RTMPClient {

	private Socket socket;
	private OutputStream out;
	private InputStream in;

	public RTMPClient(String serverAddress){
		try{
			socket = new Socket(serverAddress, 1935);
			out = socket.getOutputStream();
			//in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			in = socket.getInputStream();

			performHandshake();
		} catch(Exception e){
			System.out.println(e.getMessage());
			e.printStackTrace(System.out);
		}
	}

	public void performHandshake(){
		try{
			//C0 - Write RTMP version
			out.write(0x03);
			//C1 - Write the timestamp,zero, and 1528 random bytes
			for (int i=0; i<1536; i++){
				out.write(0x00);
			}
			
			//Read S0 - echo version
			System.out.println("Got version back from server: " + in.read());
			//Read S1 - echo C1  mostly
			System.out.print("reading handshake data...");
			for (int g = 0; g<8; g++){
				System.out.print(in.read());
			}
			byte[] S01 = new byte[1528];
			in.read(S01);
			
			//C2 - Write out the last of the handshake data
			for (int y=0; y<8; y++){
				out.write(0x00);
			}
			out.write(S01);
			
			//Read in S2
			byte[] S2 = new byte[1536];
			in.read(S2);
			
			//At this point, the handshake should be complete
			
			
		} catch(IOException e){
			e.printStackTrace();
		}
	}
}
